import cv2
import matplotlib.pyplot as plt
image_path = '3.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Error: Unable to load image.")
    exit()

# 显示原始图像
plt.figure(figsize=(12, 6))
plt.subplot(2, 2, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.axis('off')

# 1. 全局阈值化
threshold_value = 128  # 固定阈值
_, global_threshold = cv2.threshold(image, threshold_value, 255, cv2.THRESH_BINARY)
plt.subplot(2, 2, 2)
plt.title('Global Thresholding')
plt.imshow(global_threshold, cmap='gray')
plt.axis('off')

# 2. 自适应平均阈值化
adaptive_mean_threshold = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize=11, C=2)
plt.subplot(2, 2, 3)
plt.title('Adaptive Mean Thresholding')
plt.imshow(adaptive_mean_threshold, cmap='gray')
plt.axis('off')

# 3. 自适应高斯阈值化
adaptive_mean_threshold = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blockSize=11, C=2)
plt.subplot(2, 2, 4)
plt.title('Adaptive Mean Thresholding')
plt.imshow(adaptive_mean_threshold, cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()